<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文件管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="models-search">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit">新增文件</el-button>
      </el-form-item>
      <el-form-item label="类目选择">
        <el-select v-model="selectedValue" placeholder="请选择" @change="handleSelectChange">
          <el-option
            v-for="(categoryName, id) in optionMap"
            :key="id"
            :label="categoryName"
            :value="id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="downloadJsonFile">json文件模板下载</el-button>
        <el-button size="small" type="primary" @click="downloadExcelFile">excel文件模板下载</el-button>

      </el-form-item>
    </el-form>
    <!-- 标签选择器 -->

    <el-tag
      :key="index"
      v-for="(item, index) in TagClickList"
      closable
      :disable-transitions="false"
      @close="handleClose(item)">
      {{item.modelTag}}
    </el-tag>

    <!--列表-->
    <el-table  :data="listData" highlight-current-row v-loading="loading"  element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable align="center" prop="id" label="主键id" width="300" v-if="false">
      </el-table-column>
      <el-table-column sortable align="center" prop="docName" label="知识库名称" width="200">
      </el-table-column>
      <el-table-column sortable align="center" prop="categoryId" label="所属类目" :formatter="statusFormatter" width="200">
<!--        <template slot-scope="scope">-->
<!--          &lt;!&ndash; 使用映射对象来显示状态 &ndash;&gt;-->
<!--          <span>{{ statusFormatter(scope.row.categoryId) }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column sortable align="center" prop="deploy" label="状态" width="200">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.deploy ? 'green' : 'red' }">
            {{ scope.row.deploy  ? '已部署' : '未部署' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable align="center" prop="createTime" label="创建时间" width="200">
      </el-table-column>
      <el-table-column align="center" label="操作" max-width="400">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" @click="handleExtract(scope.$index, scope.row)">知识提取</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="主键" prop="id" v-show="false">
          <el-input readonly size="small" v-model="editForm.id" auto-complete="off" placeholder="请输入主键"></el-input>
        </el-form-item>
        <el-table-column sortable prop="createTime" label="创建时间" width="250" v-if="false">
        </el-table-column>
        <el-form-item label="选择类目" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择">
            <el-option
              v-for="(categoryName, id) in optionMap"
              :key="id"
              :label="categoryName"
              :value="id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="categoryName" v-if="title==='修改知识库'">
          <el-input readonly size="small" v-model="editForm.docName" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="categoryName" v-if="title==='新增知识库'">
          <el-upload
            class="upload"
            action="/api/extract/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :headers="headers"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :limit="1"
            accept=".json,.xlsx"
            :on-exceed="handleExceed"
          >

            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.json,.xlsx文件，且不超过1个</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
        <el-button size="small" @click='closeDialog("edit")'>退出</el-button>

      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from "../../components/Pagination.vue";
import {
  extractDoc,
  getAllCategoryList, modelUpload,
  wikiDocDelete,
  wikiDocList,
  wikiDocSave,
  wikiDocUpdate
} from "../../api/userMG";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      imageUrl: '',
      fileList: [], // 已上传的文件列表
      fileContent: '',
      categoryId: null,
      selectedValue: null,
      options: null,
      optionMap:[],
      editForm: {
        id: '',
        categoryId:'',
        createTime:'',
        docName:'',
        path:'',
      },
      // rules 表单验证
      rules: {
        categoryId: [
          { required: true, message: '请输入类目名称', trigger: 'blur' }
        ],
      },
      formInline: {
        pageNum: 1,
        pageSize: 10,
        categoryId:''
      },

      listData: [], //模型
      TagList:[],//所有tag列表
      TagClickList:new Set(),//选择的tag列表
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 1
      },
      headers: {
        token: localStorage.getItem('token'),
      },
    }
  },
  // 注册组件
  components: {
    Pagination,
  },

  /**
   * 数据发生改变
   */

  watch: {
  },
  /**
   * 创建完毕
   */

  created() {
    this.getdata(this.formInline)
  },
  mounted() {
    this.getCategoryList()
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    handleSelectChange() {
      this.formInline.categoryId = this.selectedValue
      this.getdata(this.formInline); // 调用查询方法
    },
    getCategoryList(){
      getAllCategoryList()
        .then(res => {
          this.loading = false
          console.log(res)
          if(res.code==null){
            this.$router.push({ name: 'login' });//跳转到查询界面
          }
          if (res.code!=0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.loading = false
            // 分页赋值
            const data = res.data;
            // 将数据组装成字典
            this.optionMap = data.reduce((acc, cur) => {
              acc[cur.id] = cur.categoryName;
              return acc;
            }, {});
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取类目列表失败，请稍后再试！')
        })
    },
    // 获取类目列表
    getdata(parameter) {
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */

      wikiDocList(parameter)
        .then(res => {
          this.loading = false
          console.log(res)
          if(res.code==null){
            this.$router.push({ name: 'login' });//跳转到查询界面
          }
          if (res.code!=0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.loading = false
            this.listData = res.data.records
            // 分页赋值
            this.pageparm.currentPage = this.formInline.current
            this.pageparm.pageSize = this.formInline.size
            this.pageparm.total = res.data.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取列表失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      console.log(parm)
      this.formInline.pageNum = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.getdata(this.formInline)

    },
    //显示编辑界面
    handleEdit: function(index, row) {
      // this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改知识库'
        this.editForm.id=row.id
        this.editForm.categoryId = row.categoryId
        this.editForm.createTime = row.createTime
        this.editForm.docName = row.docName
        this.editFormVisible = true
      } else {
        this.title = '新增知识库'
        this.editForm.id=''
        this.editForm.categoryId = ''
        this.editForm.createTime = ''
        this.editForm.docName = ''
        this.editFormVisible = true
      }
    },
    statusFormatter(row, column, cellValue, index) {
      console.log(this.optionMap)
      console.log(cellValue)
      return this.optionMap[cellValue] || '无该类目'

    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row)
          wikiDocDelete(row)
            .then(res => {
              if (res.code==200) {
                this.$message({
                  type: 'success',
                  message: '知识库已删除！'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }
              this.getdata(this.formInline)
            })
            .catch(err => {
              this.loading = false
              this.$message.error('知识库删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 知识提取
    handleExtract(index, row) {
      extractDoc(row)
        .then(res => {
          if (res.code==200) {
            this.$message({
              type: 'success',
              message: '知识提取成功！'
            })
          } else {
            this.$message({
              type: 'success',
              message: res.msg
            })
          }
          this.getdata(this.formInline)
        })
        .catch(err => {
          this.loading = false
          this.$message.error('知识提取失败，请稍后再试！')
        })
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          if(this.editForm.id){
            wikiDocUpdate(this.editForm)
              .then(res => {
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                this.loading = false
                console.log(res.success)
                if (res.code==0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据保存成功！'
                  })
                  this.editFormVisible = false
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('知识库保存失败，请稍后再试！')
              })
          }else{
            wikiDocSave(this.editForm)
              .then(res => {
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                this.loading = false
                console.log(res.success)
                if (res.code==0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据保存成功！'
                  })
                  this.editFormVisible = false
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('知识库保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
    },

    // 选中菜单
    changemenu(arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      this.checkmenu = change
    },

    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      }
    },
    handlePreview(file) {
      console.log('preview', file);
    },
    handleRemove(file, fileList) {
      // 移除文件的操作
      console.log('移除文件: ', file.name);
      this.fileList[0].name=null
      this.fileList[0].url=null
      this.fileContent=''
    },
    handleSuccess(response, file, fileList) {
      console.log('success', response, file, fileList);
      this.editForm.docName = file.name
      console.log(response.data)
      this.editForm.path = response.data
    },
    handleError(err, file, fileList) {
      console.log('error', err, file, fileList);
    },
    beforeUpload(file) {
      const isLT2M = file.size / 1024 / 1024 < 2;
      if (!isLT2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
      }
      return isLT2M;
    },
    handleExceed(files, fileList) {
      console.log(fileList)
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      if (file.raw) {
        const reader = new FileReader();
        reader.onload = e => {
          this.fileContent = e.target.result;
        };
        reader.readAsText(file.raw);
      }
    },
    downloadJsonFile() {
      // 假设你的文件位于项目的/static目录下，并且构建后仍然保留在该路径下
      // 注意：这里的路径可能是相对的，也可能是构建后的绝对路径，取决于你的构建配置
      const url = '/static/example.json'; // 使用环境变量来构建URL，如果构建配置中有设置的话

      // 创建一个临时的a标签来触发下载
      const a = document.createElement('a');
      a.href = url;
      a.download = '模板.json'; // 你可以设置下载后的文件名
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    downloadExcelFile() {
      // 假设你的文件位于项目的/static目录下，并且构建后仍然保留在该路径下
      // 注意：这里的路径可能是相对的，也可能是构建后的绝对路径，取决于你的构建配置
      const url = '/static/example1.xlsx'; // 使用环境变量来构建URL，如果构建配置中有设置的话

      // 创建一个临时的a标签来触发下载
      const a = document.createElement('a');
      a.href = url;
      a.download = '模板.xlsx'; // 你可以设置下载后的文件名
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  }

}
</script>
<style scoped>
.models-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
